package com.yshkj.payment.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 将对象转化为Json并输出
 * Created by 唐旭 on 2016/9/20.
 */
public abstract class HttpServletResponseUtils {
    private HttpServletResponseUtils() {
    }

    /**
     * 输出json数据到流中
     *
     * @param target   输出对象
     * @param response 输出的流
     */
    public static void writeObject2Json(Object target, HttpServletResponse response) {
        ObjectMapper mapper = new ObjectMapper();
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/json");
            outputStream = response.getOutputStream();
            mapper.writeValue(outputStream, target);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 将对象转换为JSON string
     *
     * @param target 需要转换的对象
     * @return 转换后的string
     */
    public static String convertObject2Json(Object target) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(target);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
